//
//  NovelInfoViewController.m
//  JianChaRiBao
//
//  Created by yuzhou on 13-5-29.
//  Copyright (c) 2013年 wzyk. All rights reserved.
//

#import "NovelInfoViewController.h"
#import "MagazineContentCell.h"
#import "UIImageView+WebCache.h"
#import <QuartzCore/QuartzCore.h>
#import "ArticleViewController.h"
#import "NovelContentCell.h"
#import "NovelContentViewController.h"
#import "DataBase.h"
#import "ASIDownloadCache.h"
#import "ActivateManager.h"
#import "ActivateViewController.h"
@interface NovelInfoViewController ()

@end

@implementation NovelInfoViewController
{
    ActivateViewController *accountViewCon;
}
- (void)showLoadingView
{
    if (loadingView.superview) {
        return;
    }
    if (loadingView == nil) {
        loadingView = [[[ABSpringLoadingView alloc] initWithFrame:contentTableView.frame] autorelease];
    }
    loadingView.alpha = 0;
    [self.view addSubview:loadingView];
    [UIView animateWithDuration:0.3 animations:^{
        loadingView.alpha = 1;
    }];
}

- (void)removeloadingView
{
    if (loadingView) {
        [UIView animateWithDuration:0.3 animations:^{
            loadingView.alpha = 0;
        } completion:^(BOOL finished) {
            [loadingView removeFromSuperview];
            loadingView = nil;
        }];
    }
}

- (void)hideActiveView
{
    [accountViewCon.activateNumTextField resignFirstResponder];
    [self becomeFirstResponder];
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = MainView.frame;
        rect.origin.x = 0;
        MainView.frame = rect;
        maskView.alpha = 0;
    }completion:^(BOOL finished) {
        
    }];
    
    //    NSLog(@"magazineEndtime:%@",[[NSUserDefaults standardUserDefaults]objectForKey:EndTime]);
    if ([[NSUserDefaults standardUserDefaults]objectForKey:EndTime] && !isActivedWhenShowMenu) {
        [self getData];
    }
}
// 点击是出现激活界面
-(void)showActiveView{
    
    if ([[NSUserDefaults standardUserDefaults]objectForKey:EndTime]) {
        isActivedWhenShowMenu = YES;
    }
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = MainView.frame;
        rect.origin.x = -280;
        MainView.frame = rect;
        
        maskView.alpha = 0.3;
    }];
    
}





- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        shouldSwipeBack = YES;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloading:) name:KDownloading object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadComplete:) name:KDownloadComplete object:nil];
    }
    return self;
}
-(void)downloading:(NSNotification *)notification{

    NSDictionary * dict = [notification object];
    NSString * idStr = [dict objectForKey:@"itemID"];
    if ([idStr isEqualToString: [_detailInfo objectForKey:@"item_id"]]) {
        showLabel.text = [NSString stringWithFormat:@"正在下载:%@/%@",[dict objectForKey:@"count"],[dict objectForKey:@"arrayCount"]];
    }
    
}
-(void)downloadComplete:(NSNotification *)notification{
    NSLog(@"downloadComplete");
    NSDictionary * dict = [notification object];
    NSString * idStr = [dict objectForKey:@"itemID"];
    if ([idStr isEqualToString: [_detailInfo objectForKey:@"item_id"]]) {
        showLabel.text = [NSString stringWithFormat:@"已完成:成功%@ 失败%@",[dict objectForKey:@"SucceseCount"],[dict objectForKey:@"failCount"]];
        downloadBtn.hidden = YES;
        downloadLabel.hidden = NO;
    }

}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    titleLabel.text = [_basicInfo valueForKey:@"item_name"];

    downloadBtn.hidden = YES;
    showLabel.hidden = YES;
    downloadLabel.hidden = YES;

    contentTableView.contentInset = UIEdgeInsetsMake(0, 0, 16, 0);
    contentTableView.tableHeaderView = headerView;
    [self getData];
    
    coverImageView.layer.shadowColor = [UIColor blackColor].CGColor;
    coverImageView.layer.shadowOpacity = 0.45;
    coverImageView.layer.shadowOffset = CGSizeMake(0, 3);
    coverImageView.layer.shadowPath = [UIBezierPath bezierPathWithRect:coverImageView.bounds].CGPath;
    coverImageView.layer.masksToBounds = NO;
    
    
    
    
    // 增加试图点击事件
    //遮盖试图点击事件
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideActiveView)];
    [maskView addGestureRecognizer:tapGesture];
    [tapGesture release];
    
    UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(hideActiveView)];
    swipeGesture.direction = UISwipeGestureRecognizerDirectionRight | UISwipeGestureRecognizerDirectionLeft;
    [maskView addGestureRecognizer:swipeGesture];
    [swipeGesture release];
    
    //阴影效果
    MainView.layer.shadowColor = [UIColor blackColor].CGColor;
    MainView.layer.shadowOpacity = 0.45;
    MainView.layer.shadowOffset = CGSizeMake(0, 6);
    MainView.layer.shadowPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, 320, 548)].CGPath;
    MainView.layer.masksToBounds = NO;
    
    accountViewCon = [[ActivateViewController alloc]initWithNibName:@"ActivateViewController" bundle:nil];
    [ActiveView addSubview:accountViewCon.view];

    
    
    
}

- (void)getData
{
    [self showLoadingView];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSDictionary *data = [[DataRequest sharedRequest] getNovelInfo:[_basicInfo objectForKey:@"item_id"]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self removeloadingView];
            if (data && [data isKindOfClass:[NSDictionary class]] && [[data objectForKey:@"result"] isKindOfClass:[NSArray class]]) {
                self.detailInfo = [[data objectForKey:@"result"]lastObject];
                self.contentArray = [self.detailInfo objectForKey:@"chapter_list"];
                [self updateDetail];
                [contentTableView reloadData];
                
                if ([[DownloadArticle shareDownloadArticle]isDownloadingWhich:[_basicInfo objectForKey:@"item_id"]]) {
                    downloadBtn.hidden = YES;
                    showLabel.hidden = NO;
                    showLabel.text = @"正在下载...";
                    NSLog(@"downloading:YES");
                }
                else {
                    NSArray * array = [[DataBase shareDB]selectInfo];
                    NSMutableArray * downloadArray = [NSMutableArray arrayWithCapacity:0];
                    for (NSDictionary * dict in array) {
                        ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[[NSString stringWithFormat:NovelChapterInfoURL,[dict objectForKey:@"nc_id"]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
                        if ([[ASIDownloadCache sharedCache] isCachedDataCurrentForRequest:request]) {
                            [downloadArray addObject:dict];
                        }
                    }
                    for (NSDictionary * dict in downloadArray) {
                        if ([[dict objectForKey:@"item_id"]isEqualToString:[_basicInfo objectForKey:@"item_id"]]) {
                            downloadBtn.hidden = YES;
                            downloadLabel.hidden = NO;
                            showLabel.hidden = YES;
                            return ;
                        }
                    }
                    downloadBtn.hidden = NO;
                }
            }
        });
    });
    
}

- (void)updateDetail
{
    NSString *imageStr = [_detailInfo objectForKey:@"cover_image"];
    //        imageStr = [NSString stringWithFormat:@"%@%@",imagePreFix,imageStr];
    imageStr = [imageStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [coverImageView setImageWithURL:[NSURL URLWithString:imageStr] placeholderImage:nil];
    titleLabel.text = [_detailInfo valueForKey:@"item_name"];
    sumLabel.text = [NSString stringWithFormat:@"共%d期",[[_detailInfo valueForKey:@"magazine_item_count"] intValue]];
    timeLabel.text = [_detailInfo valueForKey:@"author"];
    shareLabel.text = [NSString stringWithFormat:@"%d次",[[_detailInfo valueForKey:@"share_count"] intValue]];
    collectLabel.text = [NSString stringWithFormat:@"%d次",[[_detailInfo valueForKey:@"favorite_count"] intValue]];
    clickLabel.text = [NSString stringWithFormat:@"%d次",[[_detailInfo valueForKey:@"click_count"] intValue]];
    
    int rate = [[_detailInfo valueForKey:@"rank"] intValue];
    rateLabel.text = [NSString stringWithFormat:@"%d分",rate];
    for (int i = 0; i < 5; i++) {
        UIImageView *starView = (UIImageView *)[[starsView subviews] objectAtIndex:i];
        if (i * 2 + 2 <= rate) {
            starView.image = [UIImage imageNamed:@"fullStar.png"];
        }
        else if (i * 2 + 1 <= rate) {
            starView.image = [UIImage imageNamed:@"halfStar.png"];
        }
        else {
            starView.image = [UIImage imageNamed:@"emptyStar.png"];
        }
    }
}
- (IBAction)download:(id)sender {
//    downloadBtn.selected = !downloadBtn.selected;
    if (![[ActivateManager shareManager ] isActivated]) {
        ABPromptView *abp = [[ABPromptView alloc ] initWithTitle:@"您尚未激活！"];
        [abp show];
        [abp release];
        
        [self showActiveView];
        return ;
    }
    
    NSMutableArray *array  = [NSMutableArray array];
    for (NSDictionary *dict in self.contentArray) {
        if ([[dict objectForKey:@"is_view"] boolValue]) {
            [array addObject:dict];
        }
    }
    
    if (array.count == 0) {
        ABPromptView *abp = [[ABPromptView alloc ] initWithTitle:@"您尚未激活"];
        [abp show];
        [self showActiveView];
        return;
        
    }else if (array.count<self.contentArray.count){
        ABPromptView *abp = [[ABPromptView alloc]initWithTitle:[NSString stringWithFormat:@"您只能下载%ld篇文章",array.count]];
        [abp show];
        [abp release];
    }else{
        downloadBtn.hidden = YES;
        [[DownloadArticle shareDownloadArticle] downloadWithInfo:_detailInfo];
        showLabel.hidden = NO;
        showLabel.text = @"正在下载...";
    }
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _contentArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NovelContentCell *cell = (NovelContentCell *)[tableView dequeueReusableCellWithIdentifier:@"NovelContentCell"];
    if (cell == nil) {
        cell = [[[NovelContentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"NovelContentCell"] autorelease];
    }
    cell.titleLabel.text = [NSString stringWithFormat:@"%@",[[_contentArray objectAtIndex:indexPath.row] valueForKey:@"subject"]];
    
//    [UIColor blackColor];
//    [UIColor lightGrayColor]
    
    cell.titleLabel.textColor =[[[_contentArray objectAtIndex:indexPath.row] valueForKey:@"is_view"] boolValue]?[UIColor blackColor]:[UIColor lightGrayColor];
    
    
    //    [cell setIsBookmark:[[[_contentArray objectAtIndex:indexPath.row] valueForKey:@"bookflag"] boolValue]];
    [cell adjust];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *title = [[_contentArray objectAtIndex:indexPath.row] valueForKey:@"subject"];
    CGSize size = [title sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(280, 9999) lineBreakMode:NSLineBreakByWordWrapping];
    return 16 + size.height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dict = [self.contentArray objectAtIndex:indexPath.row];
    if ([[dict  objectForKey:@"is_view"] boolValue]) {
        NovelContentViewController * novelView = [[NovelContentViewController alloc]initDict:[self.contentArray objectAtIndex:indexPath.row] itemID:[_detailInfo objectForKey:@"item_id"]];
        novelView.itemID = [_detailInfo objectForKey:@"item_id"];
        novelView.contentArray = self.contentArray;
        novelView.currentIndex = indexPath.row;
        [self.navigationController pushViewController:novelView animated:YES];
        [novelView release];
    }else{
        NSLog(@"您尚未激活哦！");
        ABPromptView *abp = [[ABPromptView alloc ] initWithTitle:@"您尚未激活"];
        [abp show];
        [self showActiveView];
        return;
        
    }
}

- (IBAction)navBack
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [downloadBtn release];
    [showLabel release];
    [downloadLabel release];
    [super dealloc];
}
- (void)viewDidUnload {
    [downloadBtn release];
    downloadBtn = nil;
    [showLabel release];
    showLabel = nil;
    [downloadLabel release];
    downloadLabel = nil;
    [super viewDidUnload];
}
@end
